package com.jtpay.unionpay.product.utils.manager;


import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.os.Looper;
import android.widget.Toast;
import com.jtpay.unionpay.product.utils.LogUtil;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ExceptionUtil implements Thread.UncaughtExceptionHandler {
    private static final ThreadLocal<SimpleDateFormat> sDateFormat = new ThreadLocal<SimpleDateFormat>() {
        @SuppressLint("SimpleDateFormat")
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };
    private Context mContext;
    private Thread.UncaughtExceptionHandler mDefaultHandler;

    private ExceptionUtil() {

    }

    public static ExceptionUtil getInstance() {
        return InstanceHolder.handler;
    }

    private static void quietClose(Closeable closeable) {
        if (null != closeable) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
                ExceptionUtil.getInstance().saveExceptionFile("PayTokenException " +
                        "quietCloseIOException = " + e.getMessage());
            }
        }
    }

    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        if (!handleException(throwable) && null != mDefaultHandler) {
            mDefaultHandler.uncaughtException(thread, throwable);
        } else {
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }

    public void init(Context context) {
        mContext = context;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    private void saveFile(Throwable throwable) {
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        throwable.printStackTrace(printWriter);
        Throwable cause = throwable.getCause();
        while (null != cause) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String str = writer.toString();
        saveFile(str);
    }

    /**
     * for other class save exception message
     */
    public void saveExceptionFile(String exceptionMsg) {
        exceptionMsg = exceptionMsg + "\n";
        saveFile(exceptionMsg);
    }

    private void saveFile(String message) {
        String fileName = "crash_" + sDateFormat.get().format(new Date()) + ".log";
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath() +
                    File.separator + mContext.getPackageName();
            boolean canWrite = Environment.getExternalStorageDirectory().canWrite();
            LogUtil.log("canWrite = " + canWrite);
            File pathFile = new File(storagePath);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            File file1 = new File(pathFile, fileName);
            FileWriter fileWriter1 = null;
            try {
                fileWriter1 = new FileWriter(file1, true);
                fileWriter1.write(message);
            } catch (IOException e) {
                e.printStackTrace();
                LogUtil.log("PayTokenException saveFile " + "IOException = " + e.getMessage());
            } finally {
                quietClose(fileWriter1);
            }
        }
    }

    private boolean handleException(Throwable throwable) {
        if (null == throwable) {
            return false;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                //  ToastUtil.showShort("program quit caused by exception ");
                Toast.makeText(mContext, "program quit caused by exception ", Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        }).start();
        saveFile(throwable);
        return true;
    }

    private static class InstanceHolder {
        static ExceptionUtil handler = new ExceptionUtil();
    }

}
